import { useDraggable, type UseDraggableReturn } from 'vue-draggable-plus';
export const useDrag = (
  tree: Ref<Obj[]>,
  cb: (nodeId, targetNodeId, position) => any
) => {
  const treeMap = computed(() => {
    const map = new Map();
    const q = cloneDeep(tree.value);
    while (q.length) {
      const el = q.shift();
      map.set(el.categoryName, el);
      if (el.children?.length) {
        for (let item of el.children) {
          q.push(item);
        }
      }
    }
    console.log('%c Line:19 🍰 map', 'color:#93c0a4', map);
    return map;
  });
  const dragInit = () => {
    let nodeId, targetNodeId;
    // @ts-ignore
    useDraggable<UseDraggableReturn>('.ant-tree-list-holder-inner', [], {
      animation: 150,
      onMove({ dragged, related }) {
        const oldNode = treeMap.value.get(dragged.textContent?.trim());
        const newNode = treeMap.value.get(related.textContent?.trim());
        if (oldNode.parentId !== newNode.parentId) return false;
        nodeId = oldNode.id;
        targetNodeId = newNode.id;
      },
      async onEnd({ newIndex, oldIndex }) {
        if (nodeId && targetNodeId) {
          const list = findTree(tree.value, nodeId);
          const i = list.findIndex(item => item.id == nodeId);
          const j = list.findIndex(item => item.id == targetNodeId);
          swap(list, i, j);
          cb(nodeId, targetNodeId, oldIndex < newIndex ? 'AFTER' : 'BEFORE');
        }
      },
    });
  };
  return {
    dragInit,
  };
};

const swap = (arr, i, j) => {
  const temp = arr[i];
  arr.splice(i, 1);
  arr.splice(j, 0, temp);
};

const findTree = (list: Obj[], target) => {
  for (let item of list) {
    if (item.id == target) {
      return list;
    }
    if (item.children?.length) {
      const res = findTree(item.children, target);
      if (res) return res;
    }
  }
};
